Relative importing modules from parent folder subfolder 您所在的位置:网站首页 importing modules Relative importing modules from parent folder subfolder

Relative importing modules from parent folder subfolder

2023-03-23 08:47| 来源: 网络整理| 查看: 265

Answer a question

Given a directory structure like this

main/ common/ foo.py A/ src/ bar.py

How can I use Python's relative imports to import foo from bar? I've got a working solution by adding it to the path, but this is ugly. Is there a way to simply do with a single import in Python 2.7?

This is a more complex version of this question:

Importing modules from parent folder

Answers

The correct relative import would be this:

from ...common import foo

However, relative imports are only meant to work within one package. If main is a package, then you can use relative imports here. If main is not a package, you cannot.

Thus, if you're running a script in /main/ and doing something like import A.src.bar, then that relative import will fail with "Attempted relative import beyond toplevel package". This is because the relative import is trying to import something outside of the toplevel package A.

However, if you're running a script in / and doing something like import main.A.src.bar, then that relative import will succeed because main is now a package. In that case, the following two would be equivalent:

from ...common import foo from main.common import foo

To answer your comment: the meaning of the . doesn't change depending on where the script was run from, it changes depending on what the package structure is.



【本文地址】

公司简介

联系我们

今日新闻

    推荐新闻

    专题文章
      CopyRight 2018-2019 实验室设备网 版权所有